/**
 *  needToken = true 请求需要token
 *  needEncrypt = true 为需要加密
 *  loading = true 需要加载动画
 *  tknIncludePath 使用token的路径
 *  tknExcludePath 不使用token的路径
 */

import { getPhoneNum } from "@/utils/public";
import { Decrypt, Encrypt } from '@/utils/jmData';
import { getToken } from '@/utils/myCookie';
import errorCodeDict from './errorCode.js';
import configs from './config.js';

export default {
  domain: process.env.NODE_ENV == 'development'?configs.devDomain:configs.prodDomain,
  header: {
    'Content-Type': 'application/json; charset=utf-8',
    'Accept': 'application/json'
  },
  tknIncludePath :'', 
  tknExcludePath :'', 
  interceptor: {
    request: (options) => {
            
      options.header['X-Requested-With'] = 'XMLHttpRequest';
      options.header['Content-Type'] = 'application/json; charset=utf-8';
      
      let {loading,animate,modules,needToken,needEncrypt,tknExcludePath,tknIncludePath, ...rest} = options;
      let {checkUrl} = options;

      if (!isExcluded && (needToken || isIncluded)) {
        rest.header['Authorization'] = 'Bearer ' + uni.getStorageSync('user-token'); 
      }
      
      // 加载动画
      if(loading){
        uni.$emit('showLoading','request');
      }
      
      return rest;
    },
    response: async (response) => {
      
      // 关闭加载页面
      uni.$emit('hideLoading');
      
      // 网络请求失败
      if (response.statusCode != 200) {
        let error = new Error();
        error.code = response?.data?.code;
        error.message = response?.data?.message || response?.errMsg;
        throw error;
      }
      
      // api 返回错误编码
      if (response?.data?.code != 0) {
      
        if (response?.data?.code == 401) {
          // 清除登录状态
          uni.clearStorageSync();
          uni.$emit('login');
        }
        
        let error = new Error();
        error.code = response?.data?.code;
        error.message = `${error.code} :${response?.data?.message||response?.data?.msg}`;
        uni.showToast({
          icon: 'none',
          title: errorCodeDict[error.code]||errorCodeDict['default']||(response?.data?.message||response?.data?.msg)
        })
        throw error;
      }
      return response?.data;
    }
  }
}